package com.banfeiguanli.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.banfeiguanli.springboot.common.Constant;
import com.banfeiguanli.springboot.common.Result;
import com.banfeiguanli.springboot.entity.ClassInfo;
import com.banfeiguanli.springboot.entity.User;
import com.banfeiguanli.springboot.entity.dto.UserDTO;
import com.banfeiguanli.springboot.mapper.UserMapper;
import com.banfeiguanli.springboot.utils.RsaUtil;
import com.banfeiguanli.springboot.utils.TokenUtils;
import com.banfeiguanli.springboot.utils.MyPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service//注入springboot容器
public class UserService {
    @Autowired//注入类
    private UserMapper userMapper;

    //用户注册
    public Result userRegister(UserDTO userDTO) {
        Map<String, Object> data = new HashMap<>();
        String message = "";
        boolean registerSuccess = false;
        //使用私钥解密账号密码
        String userAccount = RsaUtil.decrypt(userDTO.getUserAccount()).trim();
        String userPWD = RsaUtil.decrypt(userDTO.getUserPWD()).trim();
        String userPWD2 = RsaUtil.decrypt(userDTO.getUserPWD2()).trim();
        userDTO.setUserAccount(userAccount);
        userDTO.setUserPWD(userPWD);
        userDTO.setUserPWD2(userPWD2);
        while (true) {
            if (userDTO.getUserName() == null || userDTO.getUserName().trim().equals("")) {
                message = "用户名不能为空！";
                break;
            }
            if (userDTO.getUserAccount() == null || userDTO.getUserAccount().trim().equals("")) {
                message = "账号不能为空！";
                break;
            }
            if (userDTO.getUserPWD() == null || userDTO.getUserPWD().trim().equals("")) {
                message = "密码不能为空！";
                break;
            }
            if (userDTO.getUserPWD2() == null || userDTO.getUserPWD2().trim().equals("")) {
                message = "确认密码不能为空！";
                break;
            }
            if (!userDTO.getUserPWD().trim().equals(userDTO.getUserPWD2().trim())) {
                message = "密码与确认密码不一致！";
                break;
            }
            if (userDTO.getUserPhone() == null || userDTO.getUserPhone().trim().equals("")) {
                message = "手机号不能为空！";
                break;
            }
            if (userAccountExist(userDTO.getUserAccount())) {
                message = "账号已存在！";
                break;
            }
            if (userPhoneExist(userDTO.getUserPhone())) {
                message = "该手机号已被注册！";
                break;
            }
            if (!registerSuccess(userDTO)) {
                message = "注册失败！";
                break;
            }
            message = "注册成功！";
            registerSuccess = true;
            break;
        }

        data.put("message", message);
        if (!registerSuccess) {
            return Result.error(message);
        }
        return Result.success(message, data);
    }

    //用户登录
    public Result userLogin(UserDTO userDTO) {
        Map<String, Object> data = new HashMap<>();
        List<User> userList = null;
        //使用私钥解密账号密码
        String userAccount = RsaUtil.decrypt(userDTO.getUserAccount()).trim();
        String userPWD = RsaUtil.decrypt(userDTO.getUserPWD()).trim();
        userDTO.setUserAccount(userAccount);
        userDTO.setUserPWD(userPWD);
        boolean loginSuccess = false;
        String message = "";

        while (true) {
            if (StrUtil.isBlank(userAccount)) {
                message = "账号不能为空！";
                break;
            }
            if (StrUtil.isBlank(userPWD)) {
                message = "密码不能为空！";
                break;
            }
            if (!userAccountExist(userAccount)) {
                message = "账号不存在！";
                break;
            }
            //利于账号和密码查询用户信息
            userDTO.setUserPWD(new MyPasswordEncoder().encode(userDTO.getUserAccount(), userDTO.getUserPWD()));
            userList = userMapper.userLogin(userDTO);
            if (userList.isEmpty()) {
                message = "密码错误！";
                break;
            }
            if (userList.size() > 1) {
                message = "系统错误！";
                break;
            }
            //登录成功
            message = "登录成功！";
            loginSuccess = true;
            break;
        }
        //登录不成功
        if (!loginSuccess) {
            return Result.error(message);
        }
        //登录成功
        User user = userList.get(0);
        //获取用户ID
        Integer userID = user.getUserID();
        //利用用户ID与密码生成token
        String token = TokenUtils.generateUserToken(userID.toString(), user.getUserPWD());
        data.put("token", token);
        //检测用户是否为班级管理员
        if ((user.getClassID() == null) && (!userIsClassAdmin(userID))) {
            user.setIsClassAdmin("否");
        } else {
            user.setIsClassAdmin("是");
        }
        //获取班级名
        String className = getUserClassNameByUserId(userID);
        user.setClassName(className);
        //用户信息放入data
        data.put("userInfo", user);
        return Result.success(message, data);
    }

    //检查账号是否存在
    private boolean userAccountExist(String userAccount) {
        List<User> userList = userMapper.userAccountExist(userAccount);
        return !userList.isEmpty();
    }

    //检查手机号是否存在
    private boolean userPhoneExist(String userPhone) {
        List<User> userList = userMapper.userPhoneExist(userPhone);
        return !userList.isEmpty();
    }

    //用户注册,插入用户信息
    private boolean registerSuccess(UserDTO userDTO) {
        //密码加密
        String encodeUserPWD = new MyPasswordEncoder().encode(userDTO.getUserAccount(), userDTO.getUserPWD());
        userDTO.setUserPWD(encodeUserPWD);
        int countChangeRow = userMapper.userRegister(userDTO);
        if (countChangeRow != 1) {
            return false;
        }
        return true;
    }

    //用户信息查询
    public Result getUserInfo(String token) {
        List<User> userList = null;
        String message = "";
        //从token中取出userId
        int userID = TokenUtils.getIdByToken(token);
        //利用userID获取用户信息
        userList = userMapper.getUserInfo(userID);
        //检测用户是否为班级管理员
        if (userList.isEmpty()) {
            return Result.error();
        }
        if ((userList.get(0).getClassID() == null) || !userIsClassAdmin(userID)) {
            userList.get(0).setIsClassAdmin("否");
        } else {
            userList.get(0).setIsClassAdmin("是");
        }
        //获取班级名
        String className = getUserClassNameByUserId(userID);
        userList.get(0).setClassName(className);
        return Result.success(userList.get(0));
    }

    //更新用户信息
    public Result updateUserInfo(UserDTO userDTO) {
        Map<String, Object> data = new HashMap<>();
        int totalChangeRow = userMapper.updateUserInfo(userDTO);
        data.put("totalChangeRow", totalChangeRow);
        if (totalChangeRow != 1)
            return Result.error("系统错误！");
        return Result.success("信息更新成功！", data);
    }

    //检查用户是否为班级管理员
    boolean userIsClassAdmin(int userID) {
        Integer classAdminID = userMapper.getClassAdminUserID(userID);
        if (classAdminID == null)
            return false;
        return userID == classAdminID;
    }

    //获取用户班级名
    String getUserClassNameByUserId(int userID) {
        String className = userMapper.getUserClassName(userID);
        if (StrUtil.isBlank(className)) {
            return "无";
        }
        return className;
    }

    //根据userId判断用户是否存在
    public boolean userExist(int userId) {
        List<User> userList = userMapper.getUserInfo(userId);
        return !userList.isEmpty();
    }

    //通过userId获取用户信息
    public List<User> getUserInfoByUserId(int userId) {
        return userMapper.getUserInfo(userId);
    }

    //获取用户已加入班级的信息
    public Result getUserClassInfo(String token) {
        Map<String, Object> data = new HashMap<>();
        List<ClassInfo> classInfoList = null;
        //从token中取出userId
        int userID = TokenUtils.getIdByToken(token);
        //利用userID获取班级信息
        classInfoList = userMapper.getUserClassInfo(userID);
        if (!classInfoList.isEmpty()) {
            data.put("userClassInfo", classInfoList);
            return Result.success(data);
        }
        return Result.error(Constant.CODE_612, "未加入任何班级！");
    }

    //获取用户管理的班级信息
    public Result getAdminClassInfo(String token) {
        Map<String, Object> data = new HashMap<>();
        List<ClassInfo> classInfoList = null;
        //从token中取出userId
        int userID = TokenUtils.getIdByToken(token);
        //判断用户是否是班级管理员
        if (!userIsClassAdmin(userID)) {
            return Result.error(Constant.CODE_620, "非班级管理员无法解散班级！");
        }
        //利用userID获取班级信息
        classInfoList = userMapper.getUserClassInfo(userID);
        if (!classInfoList.isEmpty()) {
            data.put("adminClassInfo", classInfoList);
            return Result.success(data);
        }
        return Result.error(Constant.CODE_612, "未加入任何班级！");
    }

    //获取用户信息(后台管理)
    @GetMapping("/infoForBack")
    public Result getUserInfoForBack(String token, Integer pageNumber, Integer pageSize, String searchUser) {
        Map<String, Object> data = new HashMap<>();
        //提取adminID
        Integer adminID = TokenUtils.getIdByToken(token);
        //查询数据
        pageNumber = (pageNumber - 1) * pageSize;
        List<User> userInfo = userMapper.getUserInfoForBack(pageNumber, pageSize, searchUser);
        data.put("userInfo", userInfo);
        //统计总数
        Integer userTotal = userMapper.countUserTotal(searchUser);
        data.put("userTotal", userTotal);
        return Result.success(data);
    }

    //禁封用户
    public Result banUser(UserDTO userDTO) {
        //更新用户信息
        Integer updateRoW = userMapper.banUser(userDTO);
        if (updateRoW != 1) {
            return Result.error("禁封失败！");
        }
        return Result.success("禁封成功！", null);
    }

    //解封用户
    public Result unBanUser(UserDTO userDTO) {
        //更新用户信息
        Integer updateRoW = userMapper.unBanUser(userDTO);
        if (updateRoW != 1) {
            return Result.error("解封失败！");
        }
        return Result.success("解封成功！", null);
    }
}
